<template>
  <div>
    <!-- 操作按钮 -->
    <div
      style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
      "
    >
      <div>
        <a-button type="primary" @click="showModal" style="margin-right: 10px">
          新增
        </a-button>
      </div>
      <div style="display: flex; align-items: center">
        <!-- 多个搜索框与按钮在同一行显示 -->
        <a-input
          v-model:value="query.name"
          placeholder="名称"
          style="width: 100px; margin-right: 10px"
        />
        <!-- 查询按钮 -->
        <a-button
          type="primary"
          @click="handleTableChange"
          style="margin-right: 10px"
        >
          查询
        </a-button>
        <a-button type="primary" @click="clearSearch">清空</a-button>
      </div>
    </div>

    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="data"
      :row-key="(record) => record.id"
    >
      <!-- 使用插槽来渲染操作列 -->
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'pic'">
          <span>
            <a-image :width="40" :src="record.pic" />
          </span>
        </template>
        <template v-if="column.key === 'action'">
          <span>
            <a @click="addChild(record.id)">添加子菜单</a>
            <a-divider type="vertical" />
            <a @click="update(record.id)">编辑</a>
            <a-divider type="vertical" />
            <a @click="_delete(record.id)">删除</a>
          </span>
        </template>
      </template>
    </a-table>
    <!-- 新增/修改 -->
    <a-modal
      v-model:open="visible"
      title="添加菜单"
      centered
      @ok="add"
      wrap-class-name="full-modal"
    >
      <form>
        <a-form
          :model="formData"
          :label-col="{ style: { width: '150px' } }"
          :wrapper-col="{ span: 14 }"
        >
          <a-form-item
            label="背景图"
            :rules="[{ required: false, message: '请输入背景图' }]"
          >
            <a-upload
              v-model:file-list="fileList"
              name="image"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              @change="handleChange"
            >
              <img
                v-if="formData.pic"
                :src="formData.pic"
                alt="avatar"
                style="width: 100px; height: 100px"
              />
              <div v-else>
                <loading-outlined v-if="loading"></loading-outlined>
                <plus-outlined v-else></plus-outlined>
                <div class="ant-upload-text">Upload</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item
            label="菜单名称"
            :rules="[{ required: true, message: '请输入菜单名称!' }]"
          >
            <a-input
              v-model:value="formData.name"
              placeholder="请输入菜单名称"
            />
          </a-form-item>
        </a-form>
      </form>
    </a-modal>
  </div>
</template>

<script>
  import { getMenuTree, _delete, add, get, update } from '@/api/menu'
  import { fileUpload } from '@/api/common'
  import { Modal } from 'ant-design-vue'
  import moment from 'moment'

  // 定义列的字段
  const columns = [
    {
      title: '背景图',
      key: 'pic',
      dataIndex: 'pic',
    },
    {
      title: '名称',
      key: 'name',
      dataIndex: 'name',
    },
    {
      title: '创建时间',
      key: 'createTime',
      dataIndex: 'createTime',
      customRender: (text) => {
        return moment(text.value).format('YYYY-MM-DD HH:mm:ss')
      },
    },
    {
      title: '修改时间',
      key: 'updateTime',
      dataIndex: 'updateTime',
      customRender: (text) => {
        if (text.value) {
          return moment(text.value).format('YYYY-MM-DD HH:mm:ss')
        } else {
          return text.value
        }
      },
    },
    {
      title: '操作',
      key: 'action', // 自定义渲染操作列
      fixed: 'right', // 固定右侧
    },
  ]
  export default {
    data() {
      return {
        data: [
          {
            name: 'John Brown sr.',
            children: [],
          },
        ], // 列表数据
        query: {}, //查询参数
        columns, // 表格列
        visible: false, // 显示新增删除框
        formData: {}, // 新增删除的数据框
      }
    },
    mounted() {
      this.fetch()
    },
    methods: {
      // 上传图片
      beforeUpload(file) {
        const formData = new FormData()
        formData.append('image', file)
        formData.append('label', 'menuBack')
        fileUpload(formData).then((data) => {
          this.formData.pic = data.data
        })
        console.log(file)
        return true
      },
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.loading = true
        }
        if (info.file.status === 'done') {
          // 上传完成后的操作
          this.loading = false

          // 从后台返回的响应中获取文件访问路径
          const response = info.file.response
          if (response && response.url) {
            this.formData.pic = response.url
          }
        }
        if (info.file.status === 'error') {
          // 上传出错时的操作
          this.loading = false
        }
      },
      // 添加子菜单
      addChild(id) {
        this.formData = { parentId: id }
        this.visible = true
      },
      // 打开新增框
      showModal() {
        this.formData = {}
        this.visible = true
      },
      // 修改数据
      update(id) {
        get({ id: id }).then(({ data }) => {
          // 查询单个展示
          this.formData = { ...data }
          this.visible = true
        })
      },
      // 删除数据
      _delete(id) {
        let ids
        // 此处批量跟单个删除公用，做一下判断
        if (Array.isArray(id)) {
          ids = id
        } else {
          ids = [id]
        }
        if (ids && ids.length > 0) {
          Modal.confirm({
            title: 'Confirm',
            content: '确定要删除吗？',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
              _delete(ids).then(() => {
                // 删除就清空勾选项
                this.selectedRowKeys = []
                // 重新查询数据
                this.handleTableChange(this.pagination)
              })
            },
          })
        }
      },
      // 清空查询参数
      clearSearch() {
        Object.getOwnPropertyNames(this.query).forEach((key) => {
          this.query[key] = null
        })
        this.handleTableChange(this.pagination)
      },
      // 新增/修改数据
      add() {
        // 复制一份数据
        const _formData = { ...this.formData }
        // 存在id走修改
        if (_formData.id) {
          update(_formData).then(() => {
            this.visible = false
            this.handleTableChange(this.pagination)
          })
        } else {
          add(_formData).then(() => {
            this.visible = false
            this.handleTableChange(this.pagination)
          })
        }
      },
      // 查询数据
      handleTableChange(pagination) {
        const pager = { ...this.pagination }
        pager.current = pagination.current
        this.pagination = pager
        this.fetch()
      },
      // 请求后台
      fetch() {
        getMenuTree({
          ...this.query,
        }).then(({ data }) => {
          this.data = data
        })
      },
    },
  }
</script>
<style></style>
